<?php
/**
 * @author Feng
 * @date 2012-6-16
 */
class collection_site_concept extends system_concept_abstract {
	
	public function __construct($lang) {
		parent::__construct(array('lang' => $lang), array('lang = ?' => $lang));
	}
	
	public function init() {
		$this->setRowClass('collection_site_row');
		$this->setModel('collection_site_model', 'site');
		$this->setJoinLeftModel('resource_link_model', 'link.key = site.link', 'link');
		$this->setJoinLeftModel('collection_rule_model', 'rule.id = site.rule_id', 'rule');
		$this->setModelCols('site', array('id', 'lang', 'link', 'name', 'title', 'cover', 'charset', 'description'));
		$this->setModelCols('site', array('rule_id', 'item_rule_id', 'special_rule_id', 'is_active', 'creationtime'));
		$this->setModelCols('link', array('key', 'url'));
		$this->setModelCols('rule', array('type', 'rule'));
	}
	
	public function save(collection_site_row $row) {
		$row->set('name', preg_replace('/[^\w-]/is', '', $row->get('name')));
		if(!preg_match('/[\w-]{2,50}/is', $row->getName())) {
			throw new collection_exception("Name formation error.");
		}
		if(!$row->getTitle()) {
			throw new collection_exception("SITE Title can not be Empty.");
		}
		if(!$row->getUrl()) {
			throw new collection_exception("SITE URL can not be Empty.");
		}
		if(!$row->get('rule')) {
			$row->setRule(serialize(array()));
		}
		if(!$row->getRule()->isLink($row->getUrl())) {
			throw new collection_exception("URL is NOT a correct protocol.");
		}
		$row->setIsActive(($row->get('is_active') ? 1 : 0));
		$key = system_encrypt::shortUrl($row->getUrl());
		$row->setLink($key);
		$row->setKey($key);
		if(!$row->getId() || !$row->getRuleId() || ($row->getRuleId() && !$this->getModel('rule')->fetchRow(array('id = ?' => $row->getRuleId())))) {
			$type = new collection_rule_type('index');
			$row->setType($type->getId());
			$rid = $this->getModel('rule')->insert($row->getModelData('rule'));
			$row->setRuleId($rid);
		} elseif($row->getRuleId()) {
			$this->getModel('rule')->update($row->getModelData('rule'), array('id = ?' => $row->getRuleId()));
		}
		if($row->getId()) {
			if($this->getModel('site')->fetchRow(array('id != ?' => $row->getId(), 'name = ?' => $row->getName()))) {
				throw new collection_exception("SITE Name is already Existing.");
			}
			$this->getModel('site')->update($row->getModelData('site'), array('id = ?' => $row->getId()));
		} else {
			if($this->getModel('site')->fetchRow(array('name = ?' => $row->getName()))) {
				throw new collection_exception("SITE Name is already Existing.");
			}
			$row->setCreationtime(system_date::timestamp());
			$id = $this->getModel('site')->insert($row->getModelData('site'));
			$row->setId($id);
		}
		if(!$this->getModel('link')->fetchRow(array('`key` = ?' => $key))) {
			$this->getModel('link')->insert($row->getModelData('link'));
		}
		return $row;
	}
	
	public function delete($row) {
		return ;
	}

}
